package fl.ass.service.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cmm.comm.facade.framework.api.ISysCdMapApiService;
import cmm.comm.facade.framework.condition.SysCdMapDQueryCondition;
import cmm.comm.facade.framework.dto.SysCdMapDDTO;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.fl.finance.api.IFinLoanDtlApiService;
import cn.fl.finance.api.IFinPayDtlApiService;
import cn.fl.finance.api.IFinPayDtlRApiService;
import cn.fl.finance.condition.FinPayDtlQC;
import cn.fl.finance.condition.FinPayDtlRQC;
import cn.fl.finance.constant.FinFlowDynamicTableConstant;
import cn.fl.finance.constant.FinFlowModelConstant;
import cn.fl.finance.constant.FinLoanConstant;
import cn.fl.finance.dto.FinLoanDtlDTO;
import cn.fl.finance.dto.FinPayDtlDTO;
import cn.fl.finance.dto.FinPayDtlRDTO;
import cn.fl.overdue.constant.RskTaskConstant;
import cn.fl.overdue.service.IOverdueApiService;
import cn.fl.project.api.IPrjPaySchApiService;
import cn.fl.project.condition.PrjPrdDtlSchRQC;
import cn.fl.project.constant.PrjPrdDtlConstant;
import cn.fl.project.dto.PrjPrdDtlDTO;
import cn.fl.project.dto.PrjPrdDtlSchRDTO;
import cn.fl.project.dto.PrjPrdPaySchDDTO;
import cn.fl.project.dto.PrjPrdPaySchMDTO;
import cn.fl.project.service.IPrjPrdPaySchMApiService;
import cn.fl.project.service.IProjectApiService;
import cn.fl.risknew.dto.RskUsrCstRDTO;
import cn.fl.risknew.service.IRskUsrCstRNewApiService;
import cn.fl.sue.api.ISueApplyViewApiService;
import cn.fl.sue.condition.SueApplyViewQC;
import cn.fl.sue.constant.SueDicCode;
import cn.fl.sue.dto.SueApplyViewDTO;
import cn.fl.system.api.ISysSequenceApiService;
import com.alibaba.fastjson.JSONObject;
import com.ibm.icu.math.BigDecimal;
import fl.ass.facade.dto.*;
import fl.ass.service.service.IFinLoanApplyService;
import fl.flow.facade.flow.condition.SysFlowSHQueryCondition;
import fl.flow.facade.flow.dto.FlowCompleteParamsDTO;
import fl.flow.facade.flow.dto.SysFlowSHDTO;
import fl.flow.service.flow.service.ISysFlowSHService;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.Pager;
import cmm.service.core.framework.biz.BaseBizImpl;
import cmm.service.core.framework.dao.IBaseDao;
import cmm.user.facade.system.api.ISysOrgApiService;
import cmm.user.facade.system.dto.SysOrgDTO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import fl.ass.facade.condition.AssDealCarQueryCondition;
import fl.ass.facade.condition.AssDealRedeemQueryCondition;
import fl.ass.facade.condition.AssDealSellQueryCondition;
import fl.ass.facade.condition.AssTrailCarDQueryCondition;
import fl.ass.facade.constant.InterfaceConstants;
import fl.ass.service.dao.AssDealCarMapper;
import fl.ass.service.dao.AssDealRedeemMapper;
import fl.ass.service.dao.AssDealSellMapper;
import fl.ass.service.dao.AssTrailCarBorrowMapper;
import fl.ass.service.dao.AssTrailCarDInfMapper;
import fl.ass.service.dao.AssTrailCarDMapper;
import fl.ass.service.dao.AssTrailCarMMapper;
import fl.ass.service.po.AssDealCar;
import fl.ass.service.po.AssDealRedeem;
import fl.ass.service.po.AssDealSell;
import fl.ass.service.po.AssTrailCarD;
import fl.ass.service.po.AssTrailCarDInf;
import fl.ass.service.po.AssTrailCarM;
import fl.ass.service.po.PrjPrdPaySchD;
import fl.ass.service.service.IAssTrailCarDService;
import fl.ass.service.transform.AssTrailCarBorrowTransform;
import fl.ass.service.transform.AssTrailCarDTransform;
import fl.ass.service.transform.AssTrailCarMTransform;
import fl.flow.facade.flow.api.IFlowApiService;
import fl.flow.facade.flow.constant.FlowConstant;
import fl.flow.facade.flow.dto.FlowStartParamsDTO;
import fl.flow.facade.flow.dto.FlowStartedDTO;
import org.springframework.util.StopWatch;

/**
 * @Description: 拖车信息明细表 服务层接口实现
 * @Description: 类中已经实现了简单增删改查操作,可以直接使用,如果有需要重写该方法即可：
 * @Description: 1、add(TVO entity) 2、removeById(Long id) 3、modify(DTO entity) 4、selectById(Long id)	5、searchListPage(Pager page) 7、searchList(DTO dto)   
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class AssTrailCarDServiceImpl extends BaseBizImpl<AssTrailCarD, AssTrailCarDDTO, AssTrailCarDQueryCondition> implements IAssTrailCarDService {
	
	private static final Logger logger = LoggerFactory.getLogger(IAssTrailCarDService.class);
	
	@Autowired
	private AssTrailCarMMapper assTrailCarMMapper;
	
	@Autowired
	private AssTrailCarDMapper assTrailCarDMapper;
	
	@Autowired
	private AssDealSellMapper assDealSellMapper;
	@Autowired
	private IRskUsrCstRNewApiService rskUsrCstRNewApiService;
	@Autowired
	private IOverdueApiService overdueApiService;
	
	@Autowired
	private AssDealCarMapper assDealCarMapper;
	
	@Autowired
	private AssDealRedeemMapper assDealRedeemMapper;
	
	@Autowired
	private AssTrailCarDInfMapper assTrailCarDInfMapper;
	
	@Autowired
	private AssTrailCarBorrowMapper assTrailCarBorrowMapper;
	
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;
	
	@Autowired
    private IFlowApiService flowApiService;
	
	@Autowired
	private ISysOrgApiService sysOrgApiService;//组织架构 API 暴露服务

    @Autowired
    private ISysCdMapApiService sysCdMapApiService;

    @Autowired
    private IProjectApiService projectApiService;

    @Autowired
    private ISueApplyViewApiService sueApplyViewApiService;

    @Autowired
    private IPrjPrdPaySchMApiService prjPrdPaySchMApiService;

    @Autowired
    private ISysFlowSHService sysFlowSHService;

    @Autowired
    private IFinLoanApplyService finLoanApplyService;
    @Autowired
    private ISysSequenceApiService sequenceApiService;
    @Autowired
    private IFinPayDtlRApiService finPayDtlRService;
    @Autowired
    private IFinLoanDtlApiService finLoanDtlService;
    @Autowired
    private IPrjPaySchApiService prjPaySchApiService;
    @Autowired
    private IFinPayDtlApiService finPayDtlApiService;

	@Override
	public List<AssTrailCarDDTO> searchList(AssTrailCarDQueryCondition condition) throws BaseException {
		if(null == condition) return new ArrayList<AssTrailCarDDTO>();
		List<AssTrailCarD> list = this.assTrailCarDMapper.selectList(condition);
		return AssTrailCarDTransform.toDTOList(list);
	}
	
	@Override
	public IBaseDao<AssTrailCarD,AssTrailCarDQueryCondition> getDao() {
		return this.assTrailCarDMapper;
	}

	/* (non-Javadoc)
	 * @see fl.ass.service.service.IAssTrailCarDService#findTrailCarApplyListByPage(cmm.mid.core.framework.page.Pager)
	 */
	@Override
	public Pager findTrailCarApplyListByPage(Pager page) {
        try {
            StopWatch sw = new StopWatch();
            sw.start("拖车申请sql耗时");
            List<AssTrailCarDDTO> list = this.assTrailCarDMapper.selectTrailCarApplyListByPage(page);
            sw.stop();
            if (!CollectionUtils.isNotEmpty(list)) {
                list = new ArrayList<AssTrailCarDDTO>();
            }
            SysDictionaryDTO dictionary = null;
            sw.start("拖车申请查询后设置各种状态耗时");
            for (AssTrailCarDDTO dto : list) {
                // 获取事业部名称-JL-20181105
                if (StringUtils.isNotBlank(dto.getBuOrgCd())) {
                    dto.setOrgName(this.getOrgName(dto.getBuOrgCd()));
                }

                // 处理业务类型
                if (StringUtils.isNotBlank(dto.getBusinessType())) {
                    dictionary = sysDictionaryApiService.getCode(InterfaceConstants.SYS_CODE, InterfaceConstants.ORG_CODE, InterfaceConstants.BUSINESS_TYPE_CD, dto.getBusinessType());
                    if (null != dictionary) {
                        dto.setBusinessType(dictionary.getCodeNm());
                    }
                }
                // 处理支付表状态
                if (StringUtils.isNotBlank(dto.getPayStatus())) {
                    dictionary = sysDictionaryApiService.getCode(InterfaceConstants.SYS_CODE, InterfaceConstants.ORG_CODE, InterfaceConstants.PAY_STATUS_CD, dto.getPayStatus());
                    if (null != dictionary) {
                        dto.setPayStatus(dictionary.getCodeNm());
                    }
                }

                // 处理拖车状态
                AssTrailCarDQueryCondition assTrailCarDQueryCondition = new AssTrailCarDQueryCondition();
                assTrailCarDQueryCondition.setPrjPrdDtlId(dto.getPrjPrdDtlId());
                assTrailCarDQueryCondition.setIsHis(BaseConstant.IS_YESNO_NO);
                assTrailCarDQueryCondition.setIsDel(BaseConstant.IS_YESNO_NO);
                List<AssTrailCarDDTO> assTrailCarDDTOS = this.searchList(assTrailCarDQueryCondition);
                String backStsCd = null;
                if (CollectionUtils.isNotEmpty(assTrailCarDDTOS)) {
                    backStsCd = assTrailCarDDTOS.get(0).getBackStsCd();
                    dictionary = sysDictionaryApiService.getCode(InterfaceConstants.SYS_CODE, InterfaceConstants.ORG_CODE, InterfaceConstants.BACK_STATUS_CD, backStsCd);
                    if (null != dictionary) {
                        dto.setBackStsCd(dictionary.getCodeNm());
                    }
                }

            }
            sw.stop();
            BaseLogUtils.newLogger("拖车申请底层耗时" + sw.prettyPrint()).info();
            page.setResultList(list);
            return page;
        } catch (BaseException e) {
            BaseLogUtils.newLogger("查询拖车申请列表失败").setKeys("page:" + JSON.toJSONString(page)).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        } catch (Exception e) {
            BaseLogUtils.newLogger("查询拖车申请列表失败").setKeys("page:" + JSON.toJSONString(page)).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        }
    }

	/* (non-Javadoc)
	 * @see fl.ass.service.service.IAssTrailCarDService#findTrailCarApplyListByPaySchIds(java.util.List)
	 */
	@Override
	public List<AssTrailCarDDTO> findTrailCarApplyListByPaySchIds(List<Long> paySchIds) throws BaseException{
        PrjPrdDtlSchRQC qc  = new PrjPrdDtlSchRQC();
        qc.setPaySchId(paySchIds.get(0));
        List<PrjPrdDtlSchRDTO> prjPrdDtlIdList = this.prjPrdPaySchMApiService.searchDtlSchRList(qc);
        if (CollectionUtils.isEmpty(prjPrdDtlIdList)) {
            throw new BaseException("查不到支付表对应产品明细，支付表id为：" + paySchIds.get(0));
        }
		List<AssTrailCarDDTO> list = assTrailCarDMapper.findTrailCarApplyListByPaySchIds(paySchIds, prjPrdDtlIdList.get(0).getPrjPrdDtlId());
		SysDictionaryDTO dictionary = null;
		for(AssTrailCarDDTO dto : list){
			//获取事业部名称-JL-20181105
			if(StringUtils.isNotBlank(dto.getBuOrgCd())){
				dto.setOrgName(this.getOrgName(dto.getBuOrgCd()));
			}
			
			//处理业务类型
			if(StringUtils.isNotBlank(dto.getBusinessType())){
				dictionary = sysDictionaryApiService.getCode(InterfaceConstants.SYS_CODE, InterfaceConstants.ORG_CODE, InterfaceConstants.BUSINESS_TYPE_CD, dto.getBusinessType());
				if(null != dictionary){
					dto.setBusinessType(dictionary.getCodeNm());
				}
			}
			//处理支付表状态
			if(StringUtils.isNotBlank(dto.getPayStatus())){
				dictionary = sysDictionaryApiService.getCode(InterfaceConstants.SYS_CODE, InterfaceConstants.ORG_CODE, InterfaceConstants.PAY_STATUS_CD, dto.getPayStatus());
				if(null != dictionary){
					dto.setPayStatus(dictionary.getCodeNm());
				}
			}
			//处理拖车状态
			if(StringUtils.isNotBlank(dto.getBackStsCd())){
				dictionary = sysDictionaryApiService.getCode(InterfaceConstants.SYS_CODE, InterfaceConstants.ORG_CODE, InterfaceConstants.BACK_STATUS_CD, dto.getBackStsCd());
				if(null != dictionary){
					//dto.setBackStsCd(dictionary.getCodeNm());
				}
			}
			//处理事业部-得到事业部字母简称
			if(StringUtils.isNotBlank(dto.getBuOrgCd())){
				dictionary = sysDictionaryApiService.getCode(InterfaceConstants.SYS_CODE, InterfaceConstants.ORG_CODE, InterfaceConstants.BUSINESS_ORG_CD, dto.getBuOrgCd());
				if(null != dictionary){
					dto.setOrgSimpleCode(dictionary.getCodeNm());
				}
			}
		}
		return list;
	}
	
	/* (non-Javadoc)
	 * @see fl.ass.service.service.IAssTrailCarDService#findOrgInfoByPaySchId(java.lang.Long)
	 */
	@Override
	public AssTrailCarDDTO findOrgInfoByPaySchId(Long paySchId) {
		//20181102-用户相关服务优化-JL
		AssTrailCarDDTO dto = assTrailCarDMapper.findOrgInfoByPaySchId(paySchId);
		/*
		 获取事业部简码开始
		 */
        Long prjId = dto.getPrjId();
        String buOrgCd = this.projectApiService.selectById(prjId).getBuOrgCd();
        SysCdMapDQueryCondition sysQc = new SysCdMapDQueryCondition();
        sysQc.setSysCd("11000");
        sysQc.setOrgCd("0000");
        sysQc.setmTypCd("M1003");
        sysQc.setIsValid(1);
        List<String> sCodeList = new ArrayList<>();
        sCodeList.add(buOrgCd);
        sysQc.setsCodeList(sCodeList);
        List<SysCdMapDDTO> sysCdMapDDTOS = this.sysCdMapApiService.searchSysCdMapDWithTargetList(sysQc);
        if (CollectionUtils.isNotEmpty(sysCdMapDDTOS)) {
            dto.setOrgSimpleCode(sysCdMapDDTOS.get(0).getTCode());
        }
        /*
		 获取事业部简码结束
		 */
		//获取事业部名称-JL-20181105
		if(StringUtils.isNotBlank(dto.getBuOrgCd())){
			dto.setOrgName(this.getOrgName(dto.getBuOrgCd()));
		}
		return dto;
	}

	/* (non-Javadoc)
	 * @see fl.ass.service.service.IAssTrailCarDService#updateAssTrailCarDetailInfo(fl.ass.facade.dto.AssTrailCarDDTO)
	 */
	@Override
	public void updateAssTrailCarDetailInfo(AssTrailCarDDTO dto) {
		assTrailCarDMapper.update(AssTrailCarDTransform.toPO(dto));
	}

	/* (non-Javadoc)
	 * @see fl.ass.service.service.IAssTrailCarDService#updatePayStatus(java.util.List)
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=BaseException.class)
	public void updatePayStatus(List<ProductStatusLogDTO> dtos) throws BaseException {
		if(CollectionUtils.isNotEmpty(dtos)){
			for (ProductStatusLogDTO dto : dtos) {
				// 已修改前完成的状态
				String prdStsCd = dto.getCurrentStatus();
				if (PrjPrdDtlConstant.CODE_PRJ_PRD_STS_CD_03.equals(prdStsCd)
						|| PrjPrdDtlConstant.CODE_PRJ_PRD_STS_CD_05.equals(prdStsCd)
						|| PrjPrdDtlConstant.CODE_PRJ_PRD_STS_CD_40.equals(prdStsCd)
						|| PrjPrdDtlConstant.CODE_PRJ_PRD_STS_CD_23.equals(prdStsCd)
						|| PrjPrdDtlConstant.CODE_PRJ_PRD_STS_CD_12.equals(prdStsCd)
						|| PrjPrdDtlConstant.CODE_PRJ_PRD_STS_CD_13.equals(prdStsCd)
						|| PrjPrdDtlConstant.CODE_PRJ_PRD_STS_CD_17.equals(prdStsCd)
						|| PrjPrdDtlConstant.CODE_PRJ_PRD_STS_CD_19.equals(prdStsCd)
						|| PrjPrdDtlConstant.CODE_PRJ_PRD_STS_CD_21.equals(prdStsCd)
						|| PrjPrdDtlConstant.CODE_PRJ_PRD_STS_CD_14.equals(prdStsCd)
						|| PrjPrdDtlConstant.CODE_PRJ_PRD_STS_CD_20.equals(prdStsCd)
						|| PrjPrdDtlConstant.CODE_PRJ_PRD_STS_CD_22.equals(prdStsCd)
						) {
					Long cstId = null;
					// 正常结清、提前结清、强制结清、赎回结清、已拖回
					PrjPrdDtlDTO prjPrdDtlDTO = projectApiService.selectPrjPrdDtlById(dto.getPrjPrdId());
					if (null != prjPrdDtlDTO) {
						PrjPrdPaySchMDTO prjPrdPaySchMDTO = this.prjPrdPaySchMApiService.selectPrjPrdPaySchMById(prjPrdDtlDTO.getPaySchId());
						if (null != prjPrdPaySchMDTO) {
							cstId = prjPrdPaySchMDTO.getCstId();
							if (StringUtils.isEmpty(cstId)) {
								throw new BaseException("客户id为空，prjPrdDtlId = " + dto.getPrjPrdId());
							}
						}
						RskUsrCstRDTO rskUsrCstRDTO = this.rskUsrCstRNewApiService.selectRskUsrCstRByCstId(cstId);
						if (null != rskUsrCstRDTO) {
							this.overdueApiService.sendRskTaskParamsByMq(RskTaskConstant.RSK_TASK_MQ_TOPIC, RskTaskConstant.RSK_TASK_MQ_TAG, RskTaskConstant.OUT_WAY_4, cstId, null, 2L, prdStsCd);
						} else {
							BaseLogUtils.newLogger("该客户无逾期任务数据！").setKeys("cstId:" + cstId).info();
						}
					}
				}
			}
		}
		//获取支付表前置状态
		List<AssTrailCarDDTO> payStatusList = assTrailCarDMapper.findPayListByIds(dtos);
		Map<Long,String> statusMap = new HashMap<Long,String>();
		if(null != payStatusList){
			Long prjPrdDtlId = null;
			String status = null;
			for(AssTrailCarDDTO dto : payStatusList){
				prjPrdDtlId = dto.getPrjPrdDtlId();
				status = dto.getPayStatus();
				if(null != prjPrdDtlId && StringUtils.isNotBlank(status)){
					statusMap.put(prjPrdDtlId, status);
				}
			}
		}
		//处理批量事务
		List<AssTrailCarDDTO> backList = null;
		List<AssTrailCarDDTO> settleList = null;
		List<AssTrailCarDDTO> turnNormalList = null;
		List<AssTrailCarDDTO> normalList = null;
		// 拖回转优车成功
		List<AssTrailCarDDTO> trail2DealSucc = null;
		AssTrailCarDDTO carDto = null;
		Date nowTime = new Date();
		String preStatus = null;
		String currentStatus = null;
		String opCode = null;
		for(ProductStatusLogDTO dto : dtos){
			carDto = new AssTrailCarDDTO();
			preStatus = statusMap.get(dto.getPrjPrdId());
			currentStatus = dto.getCurrentStatus();
			opCode = dto.getOpCode();
			if(StringUtils.isNotBlank(preStatus) && StringUtils.isNotBlank(currentStatus) && StringUtils.isNotBlank(opCode)){
				//设置前置状态
				dto.setPreStatus(preStatus);
				//设置对象属性
				carDto.setPayStatus(currentStatus);
				carDto.setOpCode(opCode);
				carDto.setMdfUsrId(dto.getCrtUsrId());
				carDto.setMdfTm(nowTime);
				carDto.setPrjPrdDtlId(dto.getPrjPrdId());
				if("S010602".equals(currentStatus)){
					//1、优先处理已拖回状态   操作码：OP0020-拖车申请通过   前置状态：S0106-拖车申请中，则记录拖回时间	
					if("OP0020".equals(opCode) && "S0106".equals(preStatus)){
						if(CollectionUtils.isEmpty(backList)){
							backList = new ArrayList<AssTrailCarDDTO>();
						}
						carDto.setBackDate(nowTime);
						backList.add(carDto);
						continue;
					}
					//2、拖车赎回转正常 操作码 OP0022-拖车赎回驳回发起人不通过 前置状态 S01060202-拖回赎回中，更新支付表状态为已拖回
					if("OP0022".equals(opCode) && "S01060202".equals(preStatus)){
						if(CollectionUtils.isEmpty(normalList)){
							normalList = new ArrayList<AssTrailCarDDTO>();
						}
						normalList.add(carDto);
						continue;
					}
				   //3、拖车管理处置流程 操作码 OP0021-通知打款/维护提车人信息不通过 前置状态S01060201-拖回处置中 更新支付表状态为已拖回
					if("OP0021".equals(opCode)&& "S01060201".equals(preStatus)){
						if(CollectionUtils.isEmpty(normalList)){
							normalList = new ArrayList<AssTrailCarDDTO>();
						}
						normalList.add(carDto);
						continue;
					}
					// 操作代码-数据字典组编码（OP0023：拖回转优车申请未通过）
					if(InterfaceConstants.OP_CODE_OP0023.equals(opCode)&&"S01060203".equals(preStatus)){
						if(CollectionUtils.isEmpty(normalList)){
							normalList = new ArrayList<AssTrailCarDDTO>();
						}
						normalList.add(carDto);
						continue;
					}
				}else if("S010301".equals(currentStatus) || "S010401".equals(currentStatus) || "S010501".equals(currentStatus) || "S0106020101".equals(currentStatus) || "S01060203010101".equals(currentStatus)
						|| "S0106020201".equals(currentStatus)){
					//2、处理结清状态    正常结清 || 提前结清 || 强制结清- 优车已处置 || 拖回已处置 || 赎回结清 ，则记录结清时间
					if(CollectionUtils.isEmpty(settleList)){
						settleList = new ArrayList<AssTrailCarDDTO>();
					}
					carDto.setSettleDate(nowTime);
					settleList.add(carDto);
					continue;
				}else if("S01".equals(currentStatus) && "S01060202".equals(preStatus) && "OP0009".equals(opCode)){
					//3、处理转正常状态   前置状态-拖回赎回中  前置操作码-OP0009-赎回转正常，则记录正常时间
					if(CollectionUtils.isEmpty(turnNormalList)){
						turnNormalList = new ArrayList<AssTrailCarDDTO>();
					}
					carDto.setTurnNormalDate(nowTime);
					turnNormalList.add(carDto);
					continue;
				} else if (InterfaceConstants.PAY_STATUS_CD_S0106020301.equals(currentStatus)) {
                    // 操作代码-数据字典组编码（OP0029：拖回转优车申请通过）；S0106020301：拖回已转优车
                    if (InterfaceConstants.OP_CODE_OP0029.equals(opCode) && InterfaceConstants.PAY_STATUS_CD_S01060203.equals(preStatus)) {
                        if (CollectionUtils.isEmpty(trail2DealSucc)) {
                            trail2DealSucc = new ArrayList<AssTrailCarDDTO>();
                        }
                        trail2DealSucc.add(carDto);
                        continue;
                    }
                    // 资产操作代码：优车处置不通过；资产状态：已转优车
                    if (InterfaceConstants.OP_CODE_OP0030.equals(opCode)) {
                        if (CollectionUtils.isEmpty(normalList)) {
                            normalList = new ArrayList<AssTrailCarDDTO>();
                        }
                        normalList.add(carDto);
                        continue;
                    }
                } else{
					if(null == normalList){
						normalList = new ArrayList<AssTrailCarDDTO>();
					}
					normalList.add(carDto);
				}
			}else{
				throw new BaseException("param is error: currentStatus or opCode is null");
			}
			//设置时间
			dto.setCrtTm(nowTime);
		}
		if(CollectionUtils.isNotEmpty(backList)){
			for(AssTrailCarDDTO dto : backList){
				assTrailCarDMapper.updatePayStatusByBack(dto);
			}
		}
		if(CollectionUtils.isNotEmpty(settleList)){
			for(AssTrailCarDDTO dto : settleList){
				assTrailCarDMapper.updatePayStatusBySettle(dto);
			}
		}
		if(CollectionUtils.isNotEmpty(turnNormalList)){
			for(AssTrailCarDDTO dto : turnNormalList){
				assTrailCarDMapper.updatePayStatusByTurnNormal(dto);
			}
		}
		if(CollectionUtils.isNotEmpty(normalList)){
			for(AssTrailCarDDTO dto : normalList){
                assTrailCarDMapper.updatePayStatus(dto);
			}
		}
        if(CollectionUtils.isNotEmpty(trail2DealSucc)){
            for(AssTrailCarDDTO dto : trail2DealSucc){
                assTrailCarDMapper.updatePayStatus(dto);
            }
        }
		assTrailCarDMapper.batchAddPrdStatusLog(dtos);
	}

	/* (non-Javadoc)
	 * @see fl.ass.service.service.IAssTrailCarDService#findTrailCarDetailListByIds(java.util.List)
	 */
	@Override
	public List<AssTrailCarDDTO> findTrailCarDetailListByIds(List<Long> ids) {
		//20181102-用户相关服务优化-JL
		List<AssTrailCarDDTO> dtoList = assTrailCarDMapper.findTrailCarDetailListByIds(ids);
		if(null != dtoList && dtoList.size()>0){
			for(AssTrailCarDDTO dto : dtoList){
				//获取事业部名称-JL-20181105
				if(StringUtils.isNotBlank(dto.getBuOrgCd())){
					dto.setOrgName(this.getOrgName(dto.getBuOrgCd()));
				}
			}
		}
		return dtoList;
	}

	/* (non-Javadoc)
	 * @see fl.ass.service.service.IAssTrailCarDService#saveAssTrailCar(fl.ass.facade.dto.AssTrailCarMDTO)
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=BaseException.class)
	public Long saveAssTrailCar(AssTrailCarMDTO dto) {
	    try {
            AssTrailCarM po = AssTrailCarMTransform.toPO(dto);
            if (null != po) {
                assTrailCarMMapper.insert(po);
                Long trailCarId = po.getId();
                if (null != trailCarId) {
                    //保存拖车明细信息
                    List<AssTrailCarDDTO> details = dto.getDetails();
                    if (null != details) {
                        List<Long> paySchIds = new ArrayList<Long>();
                        for (AssTrailCarDDTO detail : details) {
                            paySchIds.add(detail.getPaySchId());
                            detail.setMasterId(trailCarId);
                            detail.setBackStsCd("1");//拖车申请中
                            detail.setBackAmt(po.getBackAmt());//拖车合计费用
                            detail.setBackQty(po.getBackQty());//拖车数量
                            detail.setBackPrice(po.getBackPrice());//拖车价格
                            AssTrailCarD detailPo = AssTrailCarDTransform.toPO(detail);
                            assTrailCarDMapper.insert(detailPo);
                            Long detailId = detailPo.getId();
                            //保存申请时的逾期租金和罚息-取消保存
                            AssTrailCarDInf info = new AssTrailCarDInf();
                            info.setMasterId(trailCarId);
                            info.setDetailId(detailId);
                            //info.setOverRentAmt(detail.getOverdueAmt());
                            //info.setOverInterestAmt(detail.getPenaltyAmt());
                            assTrailCarDInfMapper.insert(info);
                        }
                        //修改原拖车明细数据的历史状态
                        if (paySchIds.size() > 0) {
                            //2018-05-21 fix 拖车明细内容为空时，造成变更所有数据的BUG
                            assTrailCarDMapper.updateTrailCarDetailHisStatus(paySchIds, trailCarId);
                        }
                    }
                    //保存拖车借款信息
                    AssTrailCarBorrowDTO assTrailCarBorrowDTO = dto.getAssTrailCarBorrowDTO();
                    if (null != assTrailCarBorrowDTO) {
                        assTrailCarBorrowDTO.setTrailCarId(trailCarId);
                        assTrailCarBorrowMapper.insert(AssTrailCarBorrowTransform.toPO(assTrailCarBorrowDTO));
                    }
                }
                return trailCarId;
            }
        } catch (BaseException e) {
            BaseLogUtils.newLogger("新增拖车信息主表数据失败").setThrowable(e).setKeys("DATA:" + JSONObject.toJSONString(dto)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        } catch (Exception e) {
            BaseLogUtils.newLogger("新增拖车信息主表数据失败").setThrowable(e).setKeys("DATA:" + JSONObject.toJSONString(dto)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        }
		return null;
	}
	
	/**
	 * 根据表名获取主键
	 */
	@Override
	public Long getPkId(String tabNm) throws BaseException {
		return assTrailCarDMapper.selectPkId(tabNm);
	}
	
	/**
     * 拖车模块-发起流程
     * @param qc
     * @return
     * @throws BaseException
     */
	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=BaseException.class)
    public DataResultDTO addTrailCarApply(AssTrailCarDQueryCondition qc) throws BaseException{
	    try {
            DataResultDTO resultDTO = null;
            //获取发起流程对象
            FlowStartParamsDTO flowStartParamsDTO = new FlowStartParamsDTO();
            flowStartParamsDTO.setBusinessKey(String.valueOf(qc.getId()));//业务主键
            flowStartParamsDTO.setAudStsCd(FlowConstant.FLOW_CHECK_STATE_IN);
            flowStartParamsDTO.setWordsInTheTable(InterfaceConstants.ASS_FLOW_S_H_ASS);
            flowStartParamsDTO.setCrtUsrId(qc.getUsrId());
            flowStartParamsDTO.setOrgCd(qc.getOrgCd());
            flowStartParamsDTO.setSysCd(qc.getSysCd());
            flowStartParamsDTO.setBuOrgCd(qc.getBuOrgCd());
            flowStartParamsDTO.setInitiator(String.valueOf(qc.getUsrId()));
            flowStartParamsDTO.setInitiatorNm(qc.getUsrNm());
            flowStartParamsDTO.setProcPriority(FlowConstant.FLOW_PRIORITY_EMERGENCY);//优先级,可以在界面定义
            //判断是什么流程-分别定义相应模块类型
            if (null != qc.getFlowModelType()) {
                flowStartParamsDTO.setModelTyp(qc.getFlowModelType());//需要和流程配置中的模块类型匹配
            } else {
                flowStartParamsDTO.setModelTyp(FlowConstant.FLOW_MODEL_TYP_ASS_APPROVAL);//需要和流程配置中的模块类型匹配
            }
            //判断卡云-将之归为重卡,专车事业部流程附加参数改为项目类型
            if (null != qc.getFlow_Map()) {
                if ("KY".equals(qc.getFlow_Map().get("orgCode"))) {
                    qc.getFlow_Map().put("orgCode", "ZK");
                }
//        	if("ZC".equals(qc.getFlow_Map().get("orgCode"))){
//        		qc.getFlow_Map().put("orgCode", qc.getPrjTypCd());
//        	}
            }
            flowStartParamsDTO.setStartParams(qc.getFlow_Map());//流程附加参数

            StringBuffer keyWords = new StringBuffer();
            SysDictionaryDTO dictionary = null;
            if (StringUtils.isNotBlank(qc.getBusinessType())) {//业务类型
                dictionary = sysDictionaryApiService.getCode(InterfaceConstants.SYS_CODE, InterfaceConstants.ORG_CODE, InterfaceConstants.BUSINESS_TYPE_CD, qc.getBusinessType());
                if (null != dictionary) {
                    keyWords.append(dictionary.getCodeNm() + FlowConstant.FLOW_TASK_BACK_USR_DISPLAY_SEPERATOR);
                }
            }
            if (StringUtils.isNotBlank(qc.getPrjTypCd())) {//项目类型
                dictionary = sysDictionaryApiService.getCode(InterfaceConstants.SYS_CODE, InterfaceConstants.ORG_CODE, InterfaceConstants.PRJ_TYP_CD, qc.getPrjTypCd());
                if (null != dictionary) {
                    keyWords.append(dictionary.getCodeNm() + FlowConstant.FLOW_TASK_BACK_USR_DISPLAY_SEPERATOR);
                }
            }
            keyWords.append(qc.getOrgName() + FlowConstant.FLOW_TASK_BACK_USR_DISPLAY_SEPERATOR);//所属事业部
            keyWords.append(qc.getPrjNm() + FlowConstant.FLOW_TASK_BACK_USR_DISPLAY_SEPERATOR);//项目名称
            keyWords.append(qc.getCstNm());//客户名称
            //设置关键字
            flowStartParamsDTO.setSearchDesc(keyWords.toString());
            //客户ID 客户名称
            flowStartParamsDTO.setCstId(String.valueOf(qc.getCstId()));
            flowStartParamsDTO.setCstNm(qc.getCstNm());
            FlowStartedDTO flowStartedDTO = this.addFlowStartGetProIntId(flowStartParamsDTO);

            List<ProductStatusLogDTO> proList = new ArrayList<ProductStatusLogDTO>();
            ProductStatusLogDTO proDto = new ProductStatusLogDTO();
            if (qc.getFlowModelType().equals(FlowConstant.FLOW_MODEL_TYP_ASS_APPROVAL)) {//拖车申请
                proDto.setCurrentStatus(InterfaceConstants.PAY_STATUS_CD_S0106);
                proDto.setOpCode(InterfaceConstants.OP_CODE_OP0019);
            } else if (qc.getFlowModelType().equals(FlowConstant.FLOW_MODEL_TYP_ZC_APPROVAL)) {//专车拖车申请
                proDto.setCurrentStatus(InterfaceConstants.PAY_STATUS_CD_S0106);
                proDto.setOpCode(InterfaceConstants.OP_CODE_OP0019);
            } else if (qc.getFlowModelType().equals(FlowConstant.FLOW_MODEL_TYP_ASS_YC)) {//转优车
                proDto.setCurrentStatus(InterfaceConstants.PAY_STATUS_CD_S01060203);
                proDto.setOpCode(InterfaceConstants.OP_CODE_OP0028);
            } else if (qc.getFlowModelType().equals(FlowConstant.FLOW_MODEL_TYP_ASS_DEAL)) {//拖车管理处置
                proDto.setCurrentStatus(InterfaceConstants.PAY_STATUS_CD_S01060201);
                proDto.setOpCode(InterfaceConstants.OP_CODE_OP0024);
            } else if (qc.getFlowModelType().equals(FlowConstant.FLOW_MODEL_TYP_ZC_DEAL)) {//专车拖车管理处置
                proDto.setCurrentStatus(InterfaceConstants.PAY_STATUS_CD_S01060201);
                proDto.setOpCode(InterfaceConstants.OP_CODE_OP0024);
            } else if (qc.getFlowModelType().equals(FlowConstant.FLOW_MODEL_TYP_ASS_DEAL_YC)) {//优车处置
                proDto.setCurrentStatus(InterfaceConstants.PAY_STATUS_CD_S010602030101);
                proDto.setOpCode(InterfaceConstants.OP_CODE_OP0031);
            } else if (qc.getFlowModelType().equals(FlowConstant.FLOW_MODEL_TYP_ASS_REDEEM)) {//赎回
                proDto.setCurrentStatus(InterfaceConstants.PAY_STATUS_CD_S01060202);
                proDto.setOpCode(InterfaceConstants.OP_CODE_OP0026);
            } else if (qc.getFlowModelType().equals(FlowConstant.FLOW_MODEL_TYP_ZC_REDEEM)) {//专车拖车赎回
                proDto.setCurrentStatus(InterfaceConstants.PAY_STATUS_CD_S01060202);
                proDto.setOpCode(InterfaceConstants.OP_CODE_OP0026);
            }
            proDto.setPrjPrdId(qc.getPrjPrdDtlId());
            proDto.setProcessInstanceCode(flowStartedDTO.getProcInstanceNo());
            proDto.setProcessInstanceId(flowStartedDTO.getProcInstanceId());
            proList.add(proDto);
//		MessageDTO<String> result = this.assTrailCarApi.updatePayStatus(proList);
//		if (!result.isSuccess()) {
//			 throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_603, "更细支付表状态失败。");
//		}
            //修改支付表状态-直接调用就可以
            updatePayStatus(proList);
            if (flowStartedDTO != null && StringUtils.isNotBlank(flowStartedDTO.getProcInstanceId())) {
                resultDTO = new DataResultDTO(String.valueOf(BaseConstant.IS_YESNO_YES));
                AssDealCarDTO assDealCarDTO = new AssDealCarDTO();
                assDealCarDTO.setProcId(flowStartedDTO.getProcInstanceId());
                assDealCarDTO.setProcNo(flowStartedDTO.getProcInstanceNo());
                resultDTO.setData(assDealCarDTO);
                if (StringUtils.isNotBlank(flowStartedDTO.getNextOperUsrNames())) {
                    resultDTO.setInfo("下一个节点操作人:" + flowStartedDTO.getNextOperUsrNames());
                } else {
                    resultDTO.setInfo("拖车模块-流程发起成功");
                }
                BaseLogUtils.newLogger("拖车模块==>流程发起成功").setKeys("流程实例id=" + flowStartedDTO.getProcInstanceId()).info();
            } else {
                BaseLogUtils.newLogger("拖车模块==>流程发起失败:").setKeys("qc=" + JSON.toJSONString(qc)).info();
                resultDTO = new DataResultDTO(String.valueOf(BaseConstant.IS_YESNO_NO), "拖车模块-流程发起失败！");
                return resultDTO;
            }
            return resultDTO;
        } catch (BaseException e) {
	        BaseLogUtils.newLogger("发起拖车模块流程失败").setKeys("qc:" + JSON.toJSONString(qc)).setThrowable(e).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
	        throw e;
        } catch (Exception e) {
            BaseLogUtils.newLogger("发起拖车模块流程失败").setKeys("qc:" + JSON.toJSONString(qc)).setThrowable(e).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        }
	}
	
	/**
     * 发起流程并返回流程实例ID
     * @param flowStartParamsDTO
     * @return
     * @throws BaseException
     */
    private FlowStartedDTO addFlowStartGetProIntId(FlowStartParamsDTO flowStartParamsDTO) throws BaseException {
        if(StringUtils.isEmpty(flowStartParamsDTO.getBusinessKey())){
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "业务数据主键必须存在!");
        }
        if(StringUtils.isEmpty(flowStartParamsDTO.getCrtUsrId().toString())){
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "用户ID必须要存在!");
        }
        if(StringUtils.isEmpty(flowStartParamsDTO.getModelTyp())){
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "流程业务分类不能为空");
        }
        if(StringUtils.isEmpty(flowStartParamsDTO.getAudStsCd())){
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "流程状态不能为空");
        }
        if(StringUtils.isEmpty(flowStartParamsDTO.getWordsInTheTable())){
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "动态表名标识不能为空!");
        }
        try {
            // 设置流程关键字   以及客户ID和名称
            BaseLogUtils.newLogger("发起流程start").setKeys("flowStartParamsDTO:" + JSON.toJSONString(flowStartParamsDTO)).info();
            DataResultDTO dataResultDTO = this.flowApiService.noTransFlowStart(flowStartParamsDTO);
            BaseLogUtils.newLogger("发起流程End").setKeys("dataResultDTO:" + JSON.toJSONString(dataResultDTO)).info();
            FlowStartedDTO flowStartedDTO = (FlowStartedDTO) dataResultDTO.getData();
            return flowStartedDTO;
        } catch (BaseException e) {
            BaseLogUtils.newLogger("拖车模块-流程发起失败").setThrowable(e).setKeys("flowStartParamsDTO:" + JSON.toJSONString(flowStartParamsDTO)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_605,e.getMessage());
        }catch (Exception e) {
            BaseLogUtils.newLogger("拖车模块-流程发起失败").setThrowable(e).setKeys("flowStartParamsDTO:" + JSON.toJSONString(flowStartParamsDTO)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_605,BaseExceptionConstant.BASE_EXCEPTION_CODE_605_NAME);
        }
    }

	/* (non-Javadoc)
	 * @see fl.ass.service.service.IAssTrailCarDService#findTrailCarListByPage(cmm.mid.core.framework.page.Pager)
	 */
	@Override
	public Pager findTrailCarListByPage(Pager page) {
		if(null != page){
			AssTrailCarDQueryCondition condition = (AssTrailCarDQueryCondition)page.getCondition();
			if(null != condition){
				Date date = new Date();
				//根据最小拖回天数获取最大的拖回时间
				Integer day = condition.getMinBackDay();
				if(null != day){
					condition.setMaxBackDate(DateUtils.addDays(date, -day));
				}
				//根据最大拖回天数获取最小的拖回时间
				day = condition.getMaxBackDay();
				if(null != day){
					condition.setMinBackDate(DateUtils.addDays(date, -day));
				}
			}
		}
		List<AssTrailCarDDTO> list = this.assTrailCarDMapper.selectTrailCarListByPage(page);
		if(!CollectionUtils.isNotEmpty(list)){
			list = new ArrayList<AssTrailCarDDTO>();
		}
		SysDictionaryDTO dictionary = null;
		for(AssTrailCarDDTO dto : list){
			//处理拖车状态
			if(StringUtils.isNotBlank(dto.getBackStsCd())){
				dictionary = sysDictionaryApiService.getCode(InterfaceConstants.SYS_CODE, InterfaceConstants.ORG_CODE, InterfaceConstants.BACK_STATUS_CD, dto.getBackStsCd());
				if(null != dictionary){
					dto.setBackStsCd(dictionary.getCodeNm());
				}
			}
			//处理处置状态
			if(StringUtils.isNotBlank(dto.getDealStsCd())){
				dictionary = sysDictionaryApiService.getCode(InterfaceConstants.SYS_CODE, InterfaceConstants.ORG_CODE, InterfaceConstants.DEAL_STATUS_CD, dto.getDealStsCd());
				if(null != dictionary){
					dto.setDealStsCd(dictionary.getCodeNm());
				}
			}else{
				dto.setDealStsCd("未处置");
			}
			//处理拖回标记
			if(StringUtils.isNotBlank(dto.getBackedFlagCd())){
				dictionary = sysDictionaryApiService.getCode(InterfaceConstants.SYS_CODE, InterfaceConstants.ORG_CODE, InterfaceConstants.BACK_FLAG_CD, dto.getBackedFlagCd());
				if(null != dictionary){
					dto.setBackedFlagCd(dictionary.getCodeNm());
				}
			}
			//处理事业部-获取事业部名称
			if(StringUtils.isNotBlank(dto.getBuOrgCd())){
				dictionary = sysDictionaryApiService.getCode(InterfaceConstants.SYS_CODE, InterfaceConstants.ORG_CODE, InterfaceConstants.BUSINESS_ORG_CD, dto.getBuOrgCd());
				if(null != dictionary){
					dto.setBuOrgCd(dictionary.getCodeNm());
					dto.setOrgName(dictionary.getCodeDesc());
				}
			}
			// 根据项目id获取最近的一条诉讼申请数据
            if (StringUtils.isNotEmpty(dto.getPrjId())) {
                SueApplyViewQC qc = new SueApplyViewQC();
                qc.setDataId(dto.getPrjId());
                SueApplyViewDTO sueApplyViewDTO = this.sueApplyViewApiService.selectLatestSueApplyView(qc);
                if (null != sueApplyViewDTO && StringUtils.isNotEmpty(sueApplyViewDTO.getSueStsCd())) {
                    dictionary = sysDictionaryApiService.getCode(InterfaceConstants.SYS_CODE, InterfaceConstants.ORG_CODE, SueDicCode.SUE0007, sueApplyViewDTO.getSueStsCd());
                    if (null != dictionary) {
                        dto.setSueStsCd(sueApplyViewDTO.getSueStsCd());
                        dto.setSueStsNm(dictionary.getCodeNm());
                    }
                }
            }
		}
		page.setResultList(list);
		return page;
	}
	/**
	 * 保存拖车实际明细表信息
	 * @param prjPrdPaySchD
	 * @return
	 */
	public MessageDTO<String> insertPrjPrdPaySchD(PrjPrdPaySchD prjPrdPaySchD) {
		MessageDTO<String> response = new MessageDTO<String>();
		try {
			Long id =  this.assTrailCarDMapper.insertPrjPrdPaySchD(prjPrdPaySchD);
			response.setId(id);//返回ID值
			response.setSuccess(true);
		} catch (Exception e) {
			response.setMessage(e.getMessage());
		}
		return response;
	}
	
	/**
     * 根据项目ID查询拖车模块相关流程业务主键列表
     * 返回值形式：Map<paySchNo,List<Long> dateIdList>
     * @param prjId
     * @return
     * @throws BaseException
     */
	@Override
    public Map<String,List<Long>> getAssDateIdList(Long prjId)throws BaseException{
		Set<String> paySchNoSet = new HashSet<String>();
		Map<String,List<Long>> resultMap = new HashMap<String,List<Long>>();
		try{
			//查询拖车审批流程业务主键集合
			AssTrailCarDQueryCondition assTrailCarQc = new AssTrailCarDQueryCondition();
			assTrailCarQc.setPrjId(prjId);
			List<AssTrailCarD> detailList = this.assTrailCarDMapper.selectList(assTrailCarQc);
			//首次遍历-获取支付表号集合
			for(AssTrailCarD po : detailList){
				//利用set不允许元素重复的性质去掉相同的元素
		        paySchNoSet.add(po.getPaySchNo());
			}
			//遍历支付表号集合
			for(String set : paySchNoSet){
				List<Long> dataIdList = new ArrayList<Long>();
				//获取某个支付表号下的业务主键集合
				for(AssTrailCarD po : detailList){
			        if(set.equals(po.getPaySchNo())){
			        	//拖车审批流程-业务主键
			        	dataIdList.add(po.getMasterId());
			    		//拖车管理处置/优车处置-业务主键
			        	AssDealSellQueryCondition assDealSellQC =new AssDealSellQueryCondition();
			    		assDealSellQC.setDetailId(po.getId());
			    		assDealSellQC.setMasterId(po.getMasterId());
			    		List<AssDealSell> sellList= this.assDealSellMapper.selectList(assDealSellQC);
			    		if(sellList != null && sellList.size() > 0){
		    				for(AssDealSell assDealSellPO : sellList){
		    					if(assDealSellPO.getId() != null){
		    						dataIdList.add(assDealSellPO.getId());
		    					}
		    				}
			    		}
			    		//转优车流程-业务主键
			    		AssDealCarQueryCondition assDealCarQC =new AssDealCarQueryCondition();
			    		assDealCarQC.setDetailId(po.getId());
			    		assDealCarQC.setMasterId(po.getMasterId());
			    		List<AssDealCar> dealCarList= this.assDealCarMapper.selectList(assDealCarQC);
			    		if(dealCarList != null && dealCarList.size() > 0){
		    				for(AssDealCar assDealCarPO : dealCarList){
		    					if(assDealCarPO.getId() != null){
		    						dataIdList.add(assDealCarPO.getId());
		    					}
		    				}
			    		}
			    		//拖车赎回流程-业务主键
			    		AssDealRedeemQueryCondition assDealRedeemQC =new AssDealRedeemQueryCondition();
			    		assDealRedeemQC.setDetailId(po.getId());
			    		assDealRedeemQC.setMasterId(po.getMasterId());
			    		List<AssDealRedeem> dealRedeemList= this.assDealRedeemMapper.selectList(assDealRedeemQC);
			    		if(dealRedeemList != null && dealRedeemList.size() > 0){
		    				for(AssDealRedeem assDealRedeemPO : dealRedeemList){
		    					if(assDealRedeemPO.getId() != null){
		    						dataIdList.add(assDealRedeemPO.getId());
		    					}
		    				}
			    		}
			        }
				}
				resultMap.put(set, dataIdList);
				BaseLogUtils.newLogger("获取拖车模块流程业务主键").setBussinessId("set:" + set).setKeys(JSON.toJSONString(dataIdList)).info();
			}
			return resultMap;
		}catch(Exception e){
		    BaseLogUtils.newLogger("获取拖车模块流程业务主键失败").setBussinessId("prjId:" + prjId).setThrowable(e).info();
		}
		return resultMap;
    }

	@Override
	public AssTrailCarDDTO selectOne(AssTrailCarDQueryCondition qc) {
		List<AssTrailCarDDTO> assTrailCarDDTOS = this.searchList(qc);
		if(CollectionUtils.isNotEmpty(assTrailCarDDTOS)){
			return assTrailCarDDTOS.get(0);
		}
		return null;
	}
	
	/**
	 * 时间：2018-11-05
	 * 开发者：JL
	 * 功能：根据orgCd获取事业部名称
	 */
	public String getOrgName(String str1){
		String orgName = "";
		//获取所有事业部（组织架构类型（SYS0006）值为“2”）
		List<SysOrgDTO> sysOrgDTOList = sysOrgApiService.searchListByOrgTypCd("2", "11000");
		//获取事业部名称
		if(sysOrgDTOList != null && sysOrgDTOList.size() >0){
			for(SysOrgDTO org : sysOrgDTOList){
				String str2 = org.getOrgCd();
				if(StringUtils.isNotBlank(str2) && str1.equals(str2)){
					orgName = org.getOrgNm();
				}
			}
		}
		return orgName;
	}

    @Override
    public List<SysFlowSHDTO> getSysFlowSHDTOS(Long dataId) throws BaseException {
	    if (StringUtils.isEmpty(dataId)) {
	        BaseLogUtils.newLogger("获取流程发起时间时无主键id").info();
	        throw new BaseException("获取流程发起时间时无主键id");
        }
        SysFlowSHQueryCondition condition = new SysFlowSHQueryCondition();
        condition.setDataId(dataId);
        condition.setSysCd(InterfaceConstants.SYS_CODE);
        condition.setWordsInTheTable("ASS");
        condition.setStatus(BaseConstant.IS_YESNO_YES);
        List<SysFlowSHDTO> sysFlowSHDTOS = null;
        try {
            sysFlowSHDTOS = this.sysFlowSHService.searchListBy(condition);
        } catch (BaseException e) {
            BaseLogUtils.newLogger("获取流程发起时间异常").setKeys("dataId:" + dataId).setThrowable(e).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        } catch (Exception e) {
            BaseLogUtils.newLogger("获取流程发起时间异常").setKeys("dataId:" + dataId).setThrowable(e).setWarning(false).error(LogExceptionEnum.API_CODE_0102);
            throw e;
        }
        if (CollectionUtils.isEmpty(sysFlowSHDTOS)) {
            BaseLogUtils.newLogger("获取流程发起时间时失败，无流程历史").setKeys("dataId:" + dataId).info();
            throw new BaseException("获取流程发起时间时失败，无流程历史");
        }
        return sysFlowSHDTOS;
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED,rollbackFor=BaseException.class)
    public void addFinLoadInfoAndFlowHistory(Long id, FlowCompleteParamsDTO flowCompleteParamsDTO){
        try {
            // 获取客户经理id
            SysFlowSHQueryCondition sysFlowCondition = new SysFlowSHQueryCondition();
            sysFlowCondition.setSysCd(flowCompleteParamsDTO.getSysCd());
            sysFlowCondition.setWordsInTheTable("ASS");
            sysFlowCondition.setDataId(flowCompleteParamsDTO.getBusinessKey());
            List<SysFlowSHDTO> searchListBy = sysFlowSHService.searchListBy(sysFlowCondition);
            if (org.apache.commons.collections.CollectionUtils.isEmpty(searchListBy)) {
                throw new BaseException("流程实例不存在:bk:" + flowCompleteParamsDTO.getBusinessKey());
            }
            BaseLogUtils.newLogger("专车拖车流程添加借款记录请求参数").setKeys("id:" + id).info();
            cn.fl.custpay.dto.DataResultDTO loanApplyFromFlow = finLoanApplyService.loanApplyFromFlow(id, searchListBy.get(0).getOrgCd());

            SysFlowSHDTO entity = new SysFlowSHDTO();
            Long sb = this.sequenceApiService.getFun("FN_GEN_SYS_FLOW_S_CAP_H_ID");
            entity.setMainId(sb);
            entity.setPDefKey(flowCompleteParamsDTO.getProcDefKey());
            entity.setPDefId(flowCompleteParamsDTO.getProcDefId());
            entity.setPInstId(flowCompleteParamsDTO.getProcInstId());

            entity.setPNo(searchListBy.get(0).getPNo());
            entity.setDataId(flowCompleteParamsDTO.getBusinessKey());
            entity.setAudStsCd("1");
            entity.setStatus(1);
            entity.setSysCd(flowCompleteParamsDTO.getSysCd());
            entity.setOrgCd(searchListBy.get(0).getOrgCd());
            entity.setBuOrgCd(searchListBy.get(0).getBuOrgCd());
            entity.setWordsInTheTable(FinFlowDynamicTableConstant.SPL_FLOW_S_H_CAP);
            //维护借款类型
            entity.setBusTyp(searchListBy.get(0).getBusTyp());
            entity.setBusTypP(FinFlowModelConstant.FLOW_LOAN_TYP_CD);
            entity.setBusTypPStatus(1);
            entity.setIsDel(0);
            entity.setCrtUsrId(searchListBy.get(0).getCrtUsrId());
            entity.setCrtTm(searchListBy.get(0).getCrtTm());
            entity.setMdfUsrId(flowCompleteParamsDTO.getCrtUsrId());
            entity.setMdfTm(new Date());
            BaseLogUtils.newLogger("添加流程历史记录表信息请求参数").setKeys(JSON.toJSONString(entity)).info();
            sysFlowSHService.add(entity);
            //添加费用明细
            List<FinPayDtlDTO> selectFinPayDtlDTO = selectFinPayDtlDTO(flowCompleteParamsDTO.getBusinessKey());
            for (FinPayDtlDTO finPayDtlDTO : selectFinPayDtlDTO) {
                FinPayDtlRQC qc = new FinPayDtlRQC();
                qc.setPayDtlId(finPayDtlDTO.getId());
                List<FinPayDtlRDTO> searchList = finPayDtlRService.selectList(qc);
                if (org.apache.commons.collections.CollectionUtils.isEmpty(searchList)) {
                    throw new BaseException("付款明细资产关联表数据有误");
                }
                //根据借款明细id查询借款明细表
                FinLoanDtlDTO selectById = finLoanDtlService.getById(finPayDtlDTO.getLoanDtlId());
                //3.循环遍历付款明细资产关联表数据
                for (FinPayDtlRDTO fdto : searchList) {
                    //4.组装支付费用信息表
                    PrjPrdPaySchDDTO dto = new PrjPrdPaySchDDTO();
                    dto.setPaySchId(fdto.getPaySchId());//添加支付表id
                    dto.setPayPd(0);//默认期次0
                    dto.setFeeAmt(new BigDecimal(fdto.getPayAmt()).doubleValue());//应付金额(费用金额)单位是元
                    dto.setFeeTypCd(selectById.getLoanTypCd());//费用类型代码
                    dto.setFeeClsCd(FinLoanConstant.FIN_LOAN_TYP_DIDC);//费用项目类型
                    dto.setArAmt(fdto.getPayAmt());//未核销金额 单位也是分

                    dto.setPaidUpAmt(0L);//已核销金额
                    dto.setIsDel(0);
                    dto.setCrtTm(new Date());//创建时间
                    dto.setCrtUsrId(flowCompleteParamsDTO.getCrtUsrId());//创建者id
                    dto.setCrtUsrName(flowCompleteParamsDTO.getCrtUsrName());//创建者名称
                    dto.setCapFlow("1");//资金流程方式 1表示收入 2表示支出
                    dto.setIsFixedAmt(1);
                    dto.setCntWayCd("3");
                    //5.新增支付费用明细表 同时返回支付明细表id
                    BaseLogUtils.newLogger("借还款->借款流程->新增支付表明细请求参数").setKeys(JSON.toJSONString(dto)).info();
                    Long idpp = prjPaySchApiService.insertPrjPrdPaySchD(dto);
                    BaseLogUtils.newLogger("借还款->借款流程->新增支付表明细返回结果").setKeys(JSON.toJSONString(idpp)).info();

                    if (idpp == null) {
                        throw new BaseException("新增支付明细表数据有误");
                    }
                    //6.修改付款明细资产关联表 添加支付明细id
                    fdto.setPaySchDtlId(idpp);
                    BaseLogUtils.newLogger("修改付款明细资产关联表请求参数").setKeys(JSON.toJSONString(fdto)).info();
                    boolean bool = finPayDtlRService.modify(fdto);
                    BaseLogUtils.newLogger("修改付款明细资产关联表返回结果").setKeys(JSON.toJSONString(bool)).info();
                }
            }
        } catch (BaseException e) {
            BaseLogUtils.newLogger("财务总监审核添加借款记录信息和流程信息异常").setKeys("id:" + id).setThrowable(e).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        } catch (Exception e) {
            BaseLogUtils.newLogger("财务总监审核添加借款记录信息和流程信息异常").setKeys("id:" + id).setThrowable(e).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        }
    }

    private List<FinPayDtlDTO> selectFinPayDtlDTO(Long id){
        FinPayDtlQC qc = new FinPayDtlQC();
        qc.setPayApplyId(id);
        qc.setIsDel(0L);
        BaseLogUtils.newLogger("条件查询付款明细表请求参数FinPayDtlId").setKeys(JSON.toJSONString(id)).info();
        List<FinPayDtlDTO> selectList = finPayDtlApiService.selectList(qc);
        return selectList;
    }

}

